﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

public partial class createimage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = createValidate(4);
        createimageM(str);
        //Response.Write(Session["valid"]);
    }
    private string createValidate(int count)
    {
        string s1 = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        string[] s1array = s1.Split(',');
        string randomcode = "";
        int temp = -1;
        Random rand = new Random();
        for (int i = 0; i < count; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(61);
            if (temp == t)
            {
                return createValidate(count);
            }
            temp = t;
            randomcode += s1array[t];
        }
        Session["valid"] = randomcode;
        return randomcode;
    }
    private void createimageM(string validatecode)
    {
        int iwidth = (int)(validatecode.Length * 19);
        Bitmap image = new Bitmap(iwidth, 30);
        Graphics graphics = Graphics.FromImage(image);
        Font font = new Font("Arial",18,FontStyle.Bold|FontStyle.Italic);
        System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush
        (new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Purple, 1.0f, true);
        graphics.Clear(System.Drawing.Color.White);
        graphics.DrawString(validatecode,font,brush,3,3);
        Random rand = new Random();
        for (int i = 0; i < 100; i++)
        {
            int x = rand.Next(image.Width);
            int y = rand.Next(image.Height);
            image.SetPixel(x, y, Color.FromArgb(rand.Next()));
        }
        graphics.DrawRectangle(new Pen(Color.DarkGray), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "image/Jpeg";
        Response.BinaryWrite(ms.ToArray());
        graphics.Dispose();
        image.Dispose();
    }
}